package com.icesoft.base.admin.controller;

import com.icesoft.base.admin.entity.SysUser;
import com.icesoft.base.admin.entity.dto.SysUserDTO;
import com.icesoft.base.admin.service.SysUserService;
import com.icesoft.base.manager.config.UrlConstant;
import com.icesoft.base.manager.entity.security.RelSysUserRole;
import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.helper.PageParam;
import com.icesoft.base.manager.helper.PageResp;
import com.icesoft.base.manager.helper.QueryBuilderUtils;
import com.icesoft.base.manager.service.security.AuthUserService;
import com.icesoft.base.manager.service.security.SysRoleService;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.util.RegexUtils;
import com.icesoft.core.dao.criteria.Page;
import com.icesoft.core.dao.criteria.QueryBuilder;
import com.icesoft.core.web.suppose.safehttp.SafeRequest;
import com.icesoft.core.web.suppose.validation.SafePassword;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户管理接口
 */
@RequestMapping("manager/sysUser")
@RestController
@AllArgsConstructor
@SafeRequest
public class SysUserManagerController {

    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final PasswordEncoder passwordEncoder;
    private final AuthUserService authUserService;
    /**
     * 通过id查询系统用户
     */
    @RequestMapping(value = UrlConstant.LOAD)
    public Resp<SysUser> load(int id) {
        return Resp.success(sysUserService.load(id));
    }

    /**
     * 修改系统用户其他信息
     */
    @PostMapping(value = UrlConstant.UPDATE)
    public Resp<Integer> update(SysUser queryParam) {
        SysUser sysUser = sysUserService.load(queryParam.getId());
        if (sysUser != null && !sysUser.getId().equals(queryParam.getId())) {
            return Resp.error("用户已存在");
        }
        sysUserService.updateNotNullProperties(queryParam);
        return Resp.success(queryParam.getId());
    }

    /**
     * 删除系统用户
     */
    @PostMapping(value = UrlConstant.DELETE)
    public Resp<?> delete(int[] ids) {
        sysUserService.delete(ids);
        return Resp.success();
    }

    /**
     * 创建系统用户
     */
    @PostMapping(UrlConstant.CREATE)
    public Resp<?> create(@Valid SysUser model) {
        if (!RegexUtils.isSafePassword(model.getPassword())) {
            return Resp.error("密码要8-32位字母、数字、特殊字符最少2种组合（不能有中文和空格）");
        }
        model.setPassword(passwordEncoder.encode(model.getPassword()));
        model.setPasswordUpdateTime(new Date());
        sysUserService.create(model);
        return Resp.success(model.getId());
    }

    /**
     * 强制下线
     */
    @PostMapping("forceLogout")
    public Resp<Integer> forceLogout(int id) {
        return Resp.success(sysUserService.forceLogout(id));
    }

    /**
     * 查询用户列表
     */
    @GetMapping(UrlConstant.QUERY)
    @SafeRequest(disable = true)
    public PageResp query(HttpServletRequest request, SysUser queryParam, String search, PageParam pageParam, Integer roleId) {
        QueryBuilder queryBuilder = QueryBuilder.get();
        if (roleId != null) {
            queryBuilder
                    .joinOn(RelSysUserRole.class, "ur", "userId")
                    .andEq("ur.roleId", roleId);
        }
        QueryBuilderUtils.addRequestParam(queryBuilder, request, queryParam);
        QueryBuilderUtils.addSearchParam(queryBuilder, search, new String[]{"email", "username", "phone", "name"});
        Page<SysUser> page = sysUserService.page(queryBuilder, pageParam);
        List<SysUserDTO> data = page.getData().stream().map(sysUserService::convertUser).collect(Collectors.toList());
        return new PageResp<>(data, page.getTotal());
    }

    /**
     * 解锁系统用户
     */
    @SafeRequest(disable = true)
    @PostMapping("unLock")
    public Resp<?> unLock(int userId) {
        SysUser sysUser = sysUserService.load(userId);
        sysUser.setLocked(false);
        sysUserService.update(sysUser);
        return new Resp<>();
    }

    /**
     * 启用/禁用系统用户
     */
    @SafeRequest(disable = true)
    @PostMapping("changeEnable")
    public Resp<?> changeEnable(int userId, boolean enable) {
        SysUser sysUser = sysUserService.load(userId);
        sysUser.setDisable(!enable);
        sysUserService.update(sysUser);
        return new Resp<>();
    }

    /**
     * 修改用户角色
     */
    @PostMapping(value = "updateUserRole")
    public Resp updateUserRole(@RequestParam int userId, @RequestParam int[] roleIds) {
        SysUser sysUser = sysUserService.load(userId);
        sysRoleService.saveUserRole(userId,sysUser.getUsername(), roleIds);
        authUserService.reloadAuthority(sysUser.getUsername());
        return Resp.success(userId);
    }

    /**
     * 修改其他用户密码
     */
    @PostMapping(value = "updatePassword")
    public Resp<?> updatePassword(int id, @SafePassword String newPassword, AuthUser authUser) {
        if (id == 1 && authUser.getId() != 1) {
            return Resp.error("不允许修改超级管理员信息");
        }
        if (authUser.getId() == id) {
            return Resp.error("请在个人中心修改");
        }
        SysUser sysUser = sysUserService.load(id);
        sysUserService.updatePassword(sysUser, newPassword);
        return Resp.success();
    }

}
